package com.yuyu.qingmangmall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.yuyu.common.constant.AuthServerConstant;
import com.yuyu.common.exception.BigCodeEnume;
import com.yuyu.common.utils.R;
import com.yuyu.common.vo.SocialMemberVo;
import com.yuyu.qingmangmall.auth.feign.MemberFeignService;
import com.yuyu.qingmangmall.auth.feign.ThirdPartFeignService;
import com.yuyu.qingmangmall.auth.vo.UserLoginVo;
import com.yuyu.qingmangmall.auth.vo.UserRegistVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {

    @Autowired
    ThirdPartFeignService thirdPartFeignService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("email") String email){

        //TODO 1. 接口防刷

        String smsCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + email);
        if (smsCode!=null){
            String s = smsCode.split("_")[1]; // 注册时的系统时间
            long l = Long.parseLong(s); // 注册时的系统时间
            if (System.currentTimeMillis() -l <60000){ // 60秒内重复为当前邮箱获取验证码
                // 60秒内不能再发
                return R.error(BigCodeEnume.SMS_CODE_EXCEPTION.getCode(),BigCodeEnume.SMS_CODE_EXCEPTION.getMessage());
            }
        }
        // 2.验证码的再次校验。redis。存key-email，value-code
        String substring = UUID.randomUUID().toString().substring(0, 5);
        // redis 缓存验证码 key：前缀+注册邮箱   value：substring+"_"+系统当前时间
        long millis = System.currentTimeMillis();
        String value = substring+"_"+millis;
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+email,value,10, TimeUnit.MINUTES);
        R r = thirdPartFeignService.sendCode(email, substring);
        return R.ok();
    }

    /**
     *  TODO 重定向携带数据，利用session原理。将数据放在session中。
     *  只要跳到下一个页面取出这个数据以后，session里面的数据就会删除掉
     *  TODO 1.分布式下的session问题
     *  RedirectAttributes  redirectAttributes：模拟重定向携带数据
     * @param userRegistVo
     * @param result
     * @param model
     * @param attributes
     * @return
     */
    @PostMapping("/register")
    public String register (@Valid UserRegistVo userRegistVo, BindingResult result, Model model, RedirectAttributes attributes){

         if (result.hasErrors()){
             Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
//             model.addAttribute("errors",errors);
            attributes.addFlashAttribute("errors",errors);
            // Request method 'POST' not supported
             // 用户注册->/register[post] ---> 转发/reg。html(路径映射默认都是get方式访问的)  post请求转发至 get请求无法转

             // 校验出错，重定向至注册页面
             return "redirect:http://auth.qingmangmall.com/reg.html";
         }

         // 判断验证码
        String email = userRegistVo.getEmail();
        String s = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + email);
        if (s!=null){ // 验证码没过期
            String smsCode = s.split("_")[0]; //验证码+"_"+millis
            if (!smsCode.equals(userRegistVo.getSmsCode())){
                Map<String, String> errors = new HashMap<>();
                errors.put("smsCode","验证码错误，请重新输入");
                attributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.qingmangmall.com/reg.html";
            }

            // 如果验证码正确要删除redis中的验证码；令牌机制
            stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + email);
            // 真正注册调用远程服务进行注册
            R register = memberFeignService.register(userRegistVo);
            if (register.getCode()!=0) {
                Map<String, String> errors = new HashMap<>();
                errors.put("msg",register.getData("msg",new TypeReference<String>(){}));
                attributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.qingmangmall.com/reg.html";
            }else {
                // 没有异常抛出
                return "redirect:http://auth.qingmangmall.com/login.html";
            }

        }else { // redis中没有该邮箱的验证码信息
            Map<String, String> errors = new HashMap<>();
            errors.put("smsCode","验证码失效，请重新获取");
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.qingmangmall.com/reg.html";
        }
//        return "redirect:http://auth.qingmangmall.com/login.html";
    }

    @GetMapping("/login.html")
    public String log(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute==null){
            return "login";
        }
        else {
            return "redirect:http://qingmangmall.com";
        }

    }

    @PostMapping("/login")
    public String login (UserLoginVo userLoginVo, RedirectAttributes redirectAttributes,
                         HttpSession session) {

        // 远程服务验证登录信息
        R login = memberFeignService.login(userLoginVo);
        if (login.getCode()==0){
            session.setAttribute(AuthServerConstant.LOGIN_USER,login.getData("member",new TypeReference<SocialMemberVo>(){}));
            // 验证成功
            return "redirect:http://qingmangmall.com";
        }else {
            // 验证失败
         Map<String,String> errors = new HashMap<>();
         errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
         redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.qingmangmall.com/login.html";
        }
    }

}
